package com.yidu.hbatsft.action;

import com.yidu.hbatsft.domain.*;
import com.yidu.hbatsft.service.*;
import com.yidu.privilege.Utils.BaseMessage;
import com.yidu.privilege.Utils.Pages;
import com.yidu.privilege.vo.UserVo;
import com.yidu.utils.FileTools;
import com.yidu.utils.Message;
import com.yidu.utils.Tools;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 介绍 运动营养控制器
 * 时间 2020年1月3日
 * 作者 谢攀
 */
@Controller
@RequestMapping("/AtsSchemeActionNutrition")
public class AtsSchemeNutritionController {
    //运动营养
    @Resource
    AtsSchemeServiceNutrition atsSchemeServiceNutrition;

    //方案对应的运动员表
    @Resource
    AtsSchemeAthleteService athleteService;

    //文件上传
    @Resource
    FileTools fele;

    //教练管理
    @Resource
    AtsEmpCoachService service;

    //运动员
    @Resource
    AtsEmpAthleteService service2;


    //专家咨询1
    @Resource
    AtsSchemeExpertService ats;

    //审核表
    @Resource
    MentalityAtsSchemeAuditService aud;

    //专家表 xy
    @Resource
    AtsEmpExpertService atsEmpExpertService;

    //专家咨询表2 xy
    @Resource
    MentalityAtsSchemeExpertService atsSchemeExpertService;


    @Resource
    MentalityAtsSchemeAthleteService atsSchemeAthleteService;

    //专家咨询表 zyh
    @Resource
    AtsSchemeExpertService se;

    /**
     * 查询所有分页
     *
     * @param pages 分页
     * @param vo 方案对象
     * @return
     */
    @ResponseBody
    @RequestMapping("selectAll")
    public Map<String, Object> findAll(Pages pages, AtsScheme vo) {

        Map<String, Object> map = new HashMap<String, Object>();

        long count = atsSchemeServiceNutrition.selectnutritioncount(vo).intValue();

        pages.setTotalRows(atsSchemeServiceNutrition.selectnutritioncount(vo).intValue());
        if (pages.getStartRows() == 0) {
            pages.setStartRows(1);
        }
        List<AtsScheme> list = atsSchemeServiceNutrition.selectnutrition(vo, pages);

        System.out.println("------------------------+" + list);
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", count); // 总行数
        map.put("data", list);
        return map;

    }

   /* *//**
     * 新增和修改
     *
     * @param vo 方案对象
     * @return
     *//*
    @ResponseBody
    @RequestMapping("insert")
    public BaseMessage add(AtsScheme vo) {

        BaseMessage bm = new BaseMessage();

        try {
             *//* //文件上传
            String Stringfile = fele.saveFile("nutrition",file11);
            vo.setFile1(Stringfile);*//*

            if (vo.getFileOne().getSize() > 0) {
                vo.setFile1(fele.saveFile("nutrition", vo.getFileOne()));
            }
            if (vo.getFileTwo().getSize() > 0) {
                vo.setFile2(fele.saveFile("nutrition", vo.getFileTwo()));
            }
            if (vo.getFileThree().getSize() > 0) {
                vo.setFile3(fele.saveFile("nutrition", vo.getFileThree()));
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


        if (vo.getSchemeId() != null && !"".equals(vo.getSchemeId())) {
            atsSchemeServiceNutrition.updatenutrition(vo);
        } else {
            bm.setState(1);
            vo.setSchemeId(170);
            vo.setSort(1);
            vo.setIsva(1);
            vo.setSchemeType("运动营养方案");
            atsSchemeServiceNutrition.insertnutrition(vo);
        }

        bm.setMsg("操作成功!");
        return bm;
    }*/


    /**
     * 逻辑删除
     * @param schemeId 方案id
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    public BaseMessage delete(Integer schemeId) {
        int s = atsSchemeServiceNutrition.deletenutrition(schemeId);
        BaseMessage bm = new BaseMessage();
        bm.setState(1);
        bm.setMsg("删除成功!");
        return bm;
    }



    /**
     * 修改显示  根据id查询
     * @param schemeId 方案id
     * @return
     */
    @RequestMapping("select")
    @ResponseBody
    public AtsScheme select(Integer schemeId) {
        AtsScheme vo = atsSchemeServiceNutrition.selectnutritionid(schemeId);
        return vo;
    }



    /**
     * 教练管理    查询所有的方法
     * @return
     */
    @RequestMapping("findAll")
    @ResponseBody
    public List<AtsEmpCoach> findAlltwo() {
        System.out.println("进入查询所有方法two");
        List<AtsEmpCoach> list = service.findAll();
        return list;
    }



    /**
     *
     * 模糊查询
     * @param pages 页数
     * @param vo 方案对象
     * @param newsTitle 方案名称
     * @return
     */
    @ResponseBody
    @RequestMapping("selectVague")
    public Map<String, Object> selectVague(Pages pages, AtsScheme vo, String newsTitle) {

        Map<String, Object> map = new HashMap<String, Object>();

        long count = atsSchemeServiceNutrition.selectnutritioncount(vo).intValue();

        pages.setTotalRows(atsSchemeServiceNutrition.selectnutritioncount(vo).intValue());
        if (pages.getStartRows() == 0) {
            pages.setStartRows(1);
        }
        vo.setSchemeName(newsTitle);
        List<AtsScheme> list = atsSchemeServiceNutrition.selectnutritionVague(newsTitle);

        map.put("code", 0);
        map.put("msg", "");
        map.put("count", count); // 总行数
        map.put("data", list);
        return map;

    }



    /**
     * 运动员查询所有
     * @param request 请求对象
     * @return
     */
    @RequestMapping("athleteselect")
    @ResponseBody
    public List<AtsEmpAthlete> athleteselect(HttpServletRequest request) {
        HttpSession session = request.getSession();
        UserVo user = (UserVo) session.getAttribute("manager");
        List<AtsEmpAthlete> list = service2.findbycoachId(user.getUsWaiid());
        return list;
    }


    /**
     * 运动营养和方案对应的运动员表批量删除
     *
     * @param ids 方案id
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteAll")
    public Message deleteAll(String ids) {
        Message m = new Message();
        int rows = 0;
        if (!"".equals(ids)) {
            String[] split = ids.split(",");
            for (String s : split) {
                rows = atsSchemeServiceNutrition.update(Integer.valueOf(s));
            }
            if (rows > 0) {
                m.setNum(1);
                m.setMsg("删除成功");
            } else {
                m.setNum(1);
                m.setMsg("删除失败");
            }
        }
        return m;
    }


    /**
     * 运动营养和方案对应的运动员表新增
     * @param vo 方案对象
     * @param at 方案对应远动员的对象
     * @param ids 远动员 id
     * @param aName 远动员姓名
     * @param request 请求对象
     * @return
     */
    @ResponseBody
    @RequestMapping("addinsert")
    public Message insert(AtsScheme vo, AtsSchemeAthlete at, String ids, String aName,HttpServletRequest request) {
        //创建BaseMessage类
        BaseMessage bm = new BaseMessage();
        //初始rows的值为0
        int rows = 0;
        try {
            //判断FileOne的长度不大于0
            if (vo.getFileOne().getSize() > 0) {
                //设置File1的值 调用fele.saveFile方法
                vo.setFile1(fele.saveFile("fele", vo.getFileOne()));
            }
            //判断FileTwo的长度不大于0
            if (vo.getFileTwo().getSize() > 0) {
                //设置File2的值 调用fele.saveFile方法
                vo.setFile2(fele.saveFile("fele", vo.getFileTwo()));
            }
            //判断FileThree的长度不大于0
            if (vo.getFileThree().getSize() > 0) {
                //设置File3的值 调用fele.saveFile方法
                vo.setFile3(fele.saveFile("fele", vo.getFileThree()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //判断SchemeId非等于空  at
        if (vo.getSchemeId() != null && !"".equals(vo.getSchemeId())) {
            //atsSchemeServiceNutrition 调用修改方法
            atsSchemeServiceNutrition.updateone(vo);
            //设置名称 把vo的名称传进去
            at.setSchemeName(vo.getSchemeName());
            //先删除在新增  athleteService 调用删除方法把SchemeId传进去
            athleteService.deletePhysics(vo.getSchemeId());
            //分割ids
            String[] split = ids.split(",");
            //分割aName
            String[] arr = aName.split(",");
            //循环arr的长度 at
            for (int i = 0; i < arr.length; i++) {
                //用数组保存split
                String s = split[i];
                //用数组保存arr
                String athleteName = arr[i];
                //设置AthleteId的值 at
                at.setAthleteId(Integer.valueOf(s));
                //设置AthleteName的值
                at.setAthleteName(athleteName);
                //设置状态
                at.setIsva(1);
                //atsSchemeServiceNutrition  调用新增
                atsSchemeServiceNutrition.addAtsSchemeAthlete(at);
            }
        } else {
            //获取Session vo
            HttpSession session = request.getSession();
            //从session中取出manager
            UserVo user = (UserVo) session.getAttribute("manager");
            //设置bm的状态
            bm.setState(1);
            //设置状态
            vo.setIsva(1);
            //设置SchemeType的方案
            vo.setSchemeType("运动营养方案");
            //教练员姓名CoachName
            vo.setCoachName(user.getUsName());
            //教练员id CoachId
            vo.setCoachId(user.getUsWaiid());
            //atsSchemeServiceNutrition 调用新增
            atsSchemeServiceNutrition.add(vo);
            //设置SchemeName的值  at
            at.setSchemeName(vo.getSchemeName());
            //设置SchemeId的值
            at.setSchemeId(vo.getSchemeId());
            //分割ids
            String[] split = ids.split(",");
            //分割aName
            String[] arr = aName.split(",");
            //循环arr的长度 at
            for (int i = 0; i < arr.length; i++) {
                //用数组保存split
                String s = split[i];
                //用数组保存arr
                String athleteName = arr[i];
                //设置AthleteId的值 at
                at.setAthleteId(Integer.valueOf(s));
                //设置AthleteName的值
                at.setAthleteName(athleteName);
                //设置状态
                at.setIsva(1);
                //atsSchemeServiceNutrition 调用新增
                atsSchemeServiceNutrition.addAtsSchemeAthlete(at);
            }

        }
        //创建Message
        Message message = new Message();
        if (rows > 0) {
            //设置Msg
            message.setMsg("操作失败");
            //设置Num
            message.setNum(1);
        } else {
            //设置Msg
            message.setMsg("操作成功");
            //设置Num
            message.setNum(0);
        }
        return message;
    }


    /**
     * 根据方案对应的运动员表的id查询
     *
     * @param id 方案id
     * @return
     */
    @ResponseBody
    @RequestMapping("selectTwo")
    public List<AtsSchemeAthlete> selectTwo(Integer id) {
        List<AtsSchemeAthlete> list = athleteService.selectbyschemeidKF(id);
        return list;
    }


    /**
     * 运用营养 查询按钮功能
     *
     * @param id 方案id
     * @return
     */
    @ResponseBody
    @RequestMapping("selectchakan")
    public AtsScheme selectchakans(Integer id) {
        AtsScheme vo = atsSchemeServiceNutrition.nutritionfindAllById(id);
        return vo;
    }



    /**
     * 反馈按钮修改
     * @param atsScheme 方案对象
     * @param rsFile 文件上传对象
     * @return
     */
    @ResponseBody
    @RequestMapping("updatefeedback")
    public Message updatefeedback(AtsScheme atsScheme, MultipartFile rsFile) {
        Message m = new Message();
        atsScheme.setResultTime(Tools.getCurDateTime());//系统当前时间
        if (rsFile.getSize() > 0) {
            try {
                atsScheme.setResultFile(fele.saveFile("nutrition", rsFile));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int rows = atsSchemeServiceNutrition.updatenutrition(atsScheme);

        if (rows > 0) {
            m.setNum(1);
            m.setMsg("反馈成功");
        } else {
            m.setNum(1);
            m.setMsg("反馈失败");
        }

        return m;
    }



    /**
     * 反馈按钮  根据id查询
     * @param id 方案id
     * @return
     */
    @RequestMapping("selectfeedback")
    @ResponseBody
    public AtsScheme selectfeedback(Integer id) {
        AtsScheme vo = atsSchemeServiceNutrition.selectnutritionid(id);
        return vo;
    }



    /**
     * 申请专家咨询 新增
     * @param atsSchemeExpert 专家对象
     * @param request 请求对象
     * @return
     */
    @ResponseBody
    @RequestMapping("addAtsSchemeExpert")
    public Message addAtsSchemeExpert(AtsSchemeExpert atsSchemeExpert, HttpServletRequest request) {
        HttpSession session = request.getSession();
        UserVo user = (UserVo) session.getAttribute("manager");
        atsSchemeExpert.setSort(1);
        atsSchemeExpert.setCreater(user.getUsName());
        atsSchemeExpert.setCreatTime(new Date());
        atsSchemeExpert.setIsva(1);
        atsSchemeExpert.setAuditState("10");
        atsSchemeExpert.setApplyForTime(Tools.getCurDateTime());
        AtsSchemeAudit audit = new AtsSchemeAudit();
        int rows = 0;
        rows = ats.insert(atsSchemeExpert);

        audit.setSaId(String.valueOf(atsSchemeExpert.getSchemeId()));
        audit.setSaName(atsSchemeExpert.getSaName());
        audit.setAuditState("10");
        audit.setSort(1);
        audit.setCreater(user.getUsName());
        audit.setCreatTime(new Date());
        audit.setIsva(1);
        rows = aud.insertSelective(audit);
        Message m = new Message();
        if (rows > 0) {
            m.setNum(1);
            m.setMsg("申请成功");
        } else {
            m.setNum(0);
            m.setMsg("申请失败");
        }
        return m;
    }



    /**
     * 申请专家咨询 修改显示
     * @param id 方案id
     * @return
     */
    @ResponseBody
    @RequestMapping("findBySchemeId")
    public AtsScheme findBySchemeId(Integer id) {
        AtsScheme atsScheme = null;
        if (id != null) {
            atsScheme = atsSchemeServiceNutrition.selectnutritionid(id);
        }
        return atsScheme;
    }


    /**
     * 领导审核
     *
     * @param asa 审核对象
     * @param ase 专家对象
     * @param request 请求对象
     * @return
     */
    @ResponseBody
    @RequestMapping("add")
    public Message add(AtsSchemeAudit asa, AtsSchemeExpert ase, HttpServletRequest request) {
        HttpSession session = request.getSession();
        UserVo user = (UserVo) session.getAttribute("manager");
        System.out.println(asa.getAuditState() + " laialaiaiaiia" + asa.getAuExp());
        asa.setAuTime(Tools.getCurDateTime());
        if ("on".equals(asa.getAuditState())) {
            asa.setAuditState("20");
            ase.setAuditState("20");
        } else {
            asa.setAuditState("21");
            ase.setAuditState("21");
        }
        asa.setSort(1);
        //这里是从session中拿
        asa.setCreater(user.getUsName());
        asa.setCreatTime(new Date());
        asa.setIsva(1);
        asa.setSaId(String.valueOf(ase.getSchemeId()));
        int i = aud.updateAuditBySaId(asa);
        ats.updateByschemeKey(ase);
        Message m = new Message();
        if (i > 0) {
            m.setMsg("成功");
            m.setNum(1);
        } else {
            m.setMsg("失败");
            m.setNum(0);
        }
        return m;
    }


    /**
     * 专家表 查询所有
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("findAllExpert")
    public List<AtsEmpExpert> findAllExpert() {
        System.out.println("12121212");
        List<AtsEmpExpert> alls = atsEmpExpertService.findAlls();
        return alls;
    }


    /**
     * 专家咨询表 根据id查询
     *
     * @param id 专家id
     * @return
     */
    @ResponseBody
    @RequestMapping("findBySeId")
    public AtsSchemeExpert findBySeId(Integer id) {
        System.out.println("aaaaaaa");
        AtsSchemeExpert ats = null;
        if (id != null) {
            ats = atsSchemeExpertService.selectByPrimaryKey(id);
            System.out.println(ats.getSaName());
        }
        return ats;
    }



    /**
     * 回复按钮
     * @param fileOne 文件上传
     * @param exp 专家对象
     * @return
     */
    @ResponseBody
    @RequestMapping("reply")
    public Message reply(MultipartFile fileOne,AtsSchemeExpert exp) {
        Message msg = new Message();
        try {
            String filePath = fele.saveFile("reply", fileOne);
            AtsSchemeExpert ase = new AtsSchemeExpert();
            ase.setAuditState("40");
            ase.setResults(filePath);
            ase.setSchemeId(exp.getSchemeId());
            int rows = atsSchemeExpertService.updateByschemeId(ase);
            System.out.println("rows:" + rows);
            if (rows > 0) {
                msg.setNum(1);
                msg.setMsg("回复成功");
            } else {
                msg.setNum(0);
                msg.setMsg("回复失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    }



    /**
     * 回复按钮 修改显示
     * @param schemeId 方案id
     * @return
     */
    @ResponseBody
    @RequestMapping("atsSchemeExpertf")
    public AtsSchemeExpert atsSchemeExpertf(Integer schemeId) {
        AtsSchemeExpert atsScheme = null;
        if (schemeId != null) {
            atsScheme = se.selectByPrimaryKey(schemeId);
        }
        return atsScheme;
    }


    /**
     * 权限管理
     * @param pageNum 页数
     * @param pageSize 总行数
     * @param atsScheme 方案对象
     * @param request 请求对象
     * @return
     */
    @ResponseBody
    @RequestMapping("jurisdiction")
    public Map<String, Object> findAll(@RequestParam("page") Integer pageNum, @RequestParam("limit") Integer pageSize, AtsScheme atsScheme, HttpServletRequest request) {
        HttpSession session = request.getSession();
        UserVo user = (UserVo) session.getAttribute("manager");
        //remark作为运动员ID
        atsScheme.setRemark(String.valueOf(user.getUsWaiid()));
        List<AtsScheme> list = null;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 0);
        map.put("msg", "");

        if (user.getUsType() != null || !"".equals(user.getUsType())) {
            if (user.getUsType().equals("专家")) {
                list = atsSchemeServiceNutrition.selectExpertnu(pageNum, pageSize, atsScheme);
                map.put("count", atsSchemeServiceNutrition.countExpertnu(atsScheme));
            } else if (user.getUsType().equals("领导")) {
                list = atsSchemeServiceNutrition.selectAuditnu(pageNum, pageSize, atsScheme);
                map.put("count", atsSchemeServiceNutrition.countAuditnu(atsScheme));
            } else if (user.getUsType().equals("运动员")) {
                list = atsSchemeServiceNutrition.selectAthletenu(pageNum, pageSize, atsScheme);
                map.put("count", atsSchemeServiceNutrition.countAthletenu(atsScheme));
            } else if (user.getUsType().equals("教练")) {
                list = atsSchemeServiceNutrition.findAllnu(pageNum, pageSize, atsScheme);
                map.put("count", atsSchemeServiceNutrition.countnu(atsScheme));
            }/*else{
                list = atsSchemeServiceNutrition.supers(pageNum, pageSize, atsScheme);
                map.put("count", atsSchemeServiceNutrition.supercountnu(atsScheme));
            }*/
            map.put("data", list);
        }
        return map;
    }


    /**
     * 修改是否查看  查看时间
     * @param id 方案对应的运动员id
     * @param schemeId 方案id
     */
    @RequestMapping("updateByAthleteId")
    @ResponseBody
    public void updateByAthleteId(Integer id,Integer schemeId){
        AtsSchemeAthlete athlete = new AtsSchemeAthlete();
        if((id!=null&&!"".equals(id))&&(schemeId!=null&&!"".equals(schemeId))){
            athlete.setAthleteId(id);
            athlete.setSchemeId(schemeId);
            athlete.setIsRead("1");
            athlete.setReadTime(Tools.getCurDateTime());
            athleteService.updateByAthleteIdnu(athlete);
        }
    }

}

